package com.glSto.service.impl;

import com.glSto.domain.ResultResponse;
import com.glSto.rep.WorkOrderResponseDTO;
import com.glSto.req.WorkOrderRequestDTO;
import com.glSto.service.WorkOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Base64;

@Service
public class WorkOrderServiceImpl implements WorkOrderService {

    @Value("${order.url}")
    private String CREATE_ORDER_URL;

    @Value("${mdm.tBasicAuth.username}")
    private String userName;
//    private String userName = "RFCEMDXPI";

    @Value("${mdm.tBasicAuth.password}")
    private String passWord;
//    private String passWord = "REmdx_2o2510";

    @Resource
    private RestTemplate restTemplate;

    private static final Logger workOrderLogger = LoggerFactory.getLogger("com.glSto.controller.WorkOrderController");

    @Override
    public ResultResponse createWorkOrder() {

        // 空请求则用默认全"1"
        WorkOrderRequestDTO req = new WorkOrderRequestDTO();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String auth = userName + ":" + passWord;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
        headers.set("Authorization", "Basic " + new String(encodedAuth));
        HttpEntity<WorkOrderRequestDTO> requestEntity = new HttpEntity<>(req, headers);
        workOrderLogger.info("请求参数：" + req);

        // 调用PO接口并返回响应
        try {
            WorkOrderResponseDTO workOrderResponseDTO = restTemplate.postForObject(CREATE_ORDER_URL, requestEntity, WorkOrderResponseDTO.class);
            workOrderLogger.info("创建工单成功");
            ResultResponse response = new ResultResponse();
            response.setCode(200);
            response.setSuccess(true);
            response.setMsg("创建工单成功");
            response.setData(workOrderResponseDTO);
            return response;
        } catch (Exception e) {
            workOrderLogger.error("创建工单失败，异常信息：{}", e.getMessage());
            ResultResponse response = new ResultResponse();
            response.setCode(500);
            response.setSuccess(false);
            response.setMsg("创建工单失败:" + e.getMessage());
            return response;
        }
    }
}